// 使用多处理器
const cluster = require('cluster')
const http = require('http')
const numCPUs = require('os').cpus().length

const rssWarn = 12 * 1024 * 1024,
    heapWarn = 10 * 1024 * 1024

var workers = {}

if (cluster.isMaster) {
    for (let i = 0; i < numCPUs; i++) {
        createWorker()
    }
    setInterval(()=>{
        let time = new Date().getTime()
        for(const pid in workers) {
            if (workers.hasOwnProperty(pid) && workers[pid].lastCb + 5000 < time) {
                console.log('Long running worker ' + pid + ' killed')
                workers[pid].worker.kill()
                delete workers[pid]
                createWorker()
            }
        }

    },1000)

    cluster.on('death', worker=>{
        console.log('worker ' + worker.pid + ' died')
    })
} else {
    http.Server((req,res)=>{
        res.writeHead(200)
        res.end('hello world!')
    }).listen(8080)

    setInterval((report) => {
        process.send({memory: process.memoryUsage(), process: process.pid})
    }, 1000);
}

function createWorker(){
    const worker = cluster.fork()
    console.log('Created worker: ' + worker.process.pid)
    workers[worker.process.pid] = {worker, lastCb: new Date().getTime() - 1000}
    worker.on('message',m=>{
        if (m.cmd === 'resportMem') {
            worker[m.process].lastCb = new Date().getTime()
            if (m.memory.rss > rssWarn) {
                console.log('worker '+m.process+' using too much memory.')
            }
        }
    })
}